'use client'

import React, { useState, useRef, useEffect } from 'react'
import {
    Card,
    Typography,
    Space,
    Button,
    Select,
    Slider,
    Switch,
    Row,
    Col,
    Tooltip,
    Alert,
    Spin
} from 'antd'
import {
    ZoomInOutlined,
    ZoomOutOutlined,
    ReloadOutlined,
    FullscreenOutlined,
    EyeOutlined,
    EyeInvisibleOutlined
} from '@ant-design/icons'
import { Detection, Classification, Segmentation, TaskResult } from '@/types/task'

const { Text } = Typography
const { Option } = Select

interface ResultVisualizationProps {
    taskType: 'detection' | 'classification' | 'segmentation'
    results: TaskResult[]
    imageData?: ArrayBuffer
    onExport?: (format: string) => void
}

interface ViewerState {
    zoom: number
    pan: [number, number]
    showOverlay: boolean
    overlayOpacity: number
    selectedClasses: string[]
    confidenceThreshold: number
}

export const ResultVisualization: React.FC<ResultVisualizationProps> = ({
    taskType,
    results,
    imageData,
    onExport
}) => {
    const canvasRef = useRef<HTMLCanvasElement>(null)
    const overlayCanvasRef = useRef<HTMLCanvasElement>(null)
    // const containerRef = useRef<HTMLDivElement>(null) // 暂时未使用

    const [viewerState, setViewerState] = useState<ViewerState>({
        zoom: 1.0,
        pan: [0, 0],
        showOverlay: true,
        overlayOpacity: 0.7,
        selectedClasses: [],
        confidenceThreshold: 0.5
    })

    const [loading] = useState(false)
    const [availableClasses, setAvailableClasses] = useState<string[]>([])

    useEffect(() => {
        // 提取所有可用的类别
        const classes = new Set<string>()
        results.forEach(result => {
            if (result.data?.detections) {
                result.data.detections.forEach(det => classes.add(det.class))
            }
            if (result.data?.classifications) {
                result.data.classifications.forEach(cls => classes.add(cls.class))
            }
            if (result.data?.segmentations) {
                result.data.segmentations.forEach(seg =>
                    seg.classes.forEach(cls => classes.add(cls))
                )
            }
        })
        const classArray = Array.from(classes)
        setAvailableClasses(classArray)
        setViewerState(prev => ({ ...prev, selectedClasses: classArray }))
    }, [results])

    useEffect(() => {
        drawVisualization()
    }, [viewerState, results, imageData])

    const drawVisualization = () => {
        const canvas = canvasRef.current
        const overlayCanvas = overlayCanvasRef.current
        if (!canvas || !overlayCanvas) return

        const ctx = canvas.getContext('2d')
        const overlayCtx = overlayCanvas.getContext('2d')
        if (!ctx || !overlayCtx) return

        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height)

        // 绘制基础图像（占位）
        drawBaseImage(ctx, canvas.width, canvas.height)

        // 绘制结果覆盖层
        if (viewerState.showOverlay) {
            drawResultOverlay(overlayCtx, overlayCanvas.width, overlayCanvas.height)
        }
    }

    const drawBaseImage = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
        // 绘制占位图像
        ctx.fillStyle = '#f0f0f0'
        ctx.fillRect(0, 0, width, height)

        // 绘制网格
        ctx.strokeStyle = '#ddd'
        ctx.lineWidth = 1
        for (let i = 0; i < width; i += 50) {
            ctx.beginPath()
            ctx.moveTo(i, 0)
            ctx.lineTo(i, height)
            ctx.stroke()
        }
        for (let i = 0; i < height; i += 50) {
            ctx.beginPath()
            ctx.moveTo(0, i)
            ctx.lineTo(width, i)
            ctx.stroke()
        }

        // 绘制占位文字
        ctx.fillStyle = '#666'
        ctx.font = '16px Arial'
        ctx.textAlign = 'center'
        ctx.fillText('医学影像显示区域', width / 2, height / 2 - 10)
        ctx.fillText('(等待后端影像数据)', width / 2, height / 2 + 10)
    }

    const drawResultOverlay = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
        ctx.globalAlpha = viewerState.overlayOpacity

        results.forEach(result => {
            if (result.data) {
                switch (taskType) {
                    case 'detection':
                        drawDetections(ctx, result.data.detections || [], width, height)
                        break
                    case 'segmentation':
                        drawSegmentations(ctx, result.data.segmentations || [], width, height)
                        break
                    case 'classification':
                        drawClassifications(ctx, result.data.classifications || [], width, height)
                        break
                }
            }
        })

        ctx.globalAlpha = 1.0
    }

    const drawDetections = (ctx: CanvasRenderingContext2D, detections: Detection[], width: number, height: number) => {
        detections.forEach((detection, index) => {
            if (detection.confidence < viewerState.confidenceThreshold) return
            if (!viewerState.selectedClasses.includes(detection.class)) return

            const [x, y, w, h] = detection.bbox
            const color = getClassColor(detection.class, index)

            // 绘制检测框
            ctx.strokeStyle = color
            ctx.lineWidth = 2
            ctx.strokeRect(x * width / 512, y * height / 512, w * width / 512, h * height / 512)

            // 绘制标签背景
            const labelText = `${detection.class} ${(detection.confidence * 100).toFixed(1)}%`
            ctx.font = '12px Arial'
            const textMetrics = ctx.measureText(labelText)
            const labelWidth = textMetrics.width + 8
            const labelHeight = 20

            ctx.fillStyle = color
            ctx.fillRect(x * width / 512, y * height / 512 - labelHeight, labelWidth, labelHeight)

            // 绘制标签文字
            ctx.fillStyle = 'white'
            ctx.textAlign = 'left'
            ctx.fillText(labelText, x * width / 512 + 4, y * height / 512 - 6)
        })
    }

    const drawSegmentations = (ctx: CanvasRenderingContext2D, segmentations: Segmentation[], width: number, height: number) => {
        segmentations.forEach((segmentation, index) => {
            segmentation.classes.forEach(className => {
                if (!viewerState.selectedClasses.includes(className)) return

                const color = segmentation.colors[className] || getClassColor(className, index)

                // 绘制分割区域（占位）
                ctx.fillStyle = color
                ctx.globalAlpha = 0.3

                // 模拟分割区域
                const regionCount = Math.floor(Math.random() * 5) + 1
                for (let i = 0; i < regionCount; i++) {
                    const x = Math.random() * width * 0.8
                    const y = Math.random() * height * 0.8
                    const w = Math.random() * 100 + 50
                    const h = Math.random() * 100 + 50

                    ctx.fillRect(x, y, w, h)
                }

                ctx.globalAlpha = viewerState.overlayOpacity
            })
        })
    }

    const drawClassifications = (ctx: CanvasRenderingContext2D, classifications: Classification[], width: number, height: number) => {
        if (classifications.length === 0) return

        const classification = classifications[0]
        if (!viewerState.selectedClasses.includes(classification.class)) return

        // 在右上角显示分类结果
        const padding = 20
        const boxWidth = 200
        const boxHeight = 80

        ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'
        ctx.fillRect(width - boxWidth - padding, padding, boxWidth, boxHeight)

        ctx.fillStyle = 'white'
        ctx.font = 'bold 14px Arial'
        ctx.textAlign = 'left'
        ctx.fillText('分类结果:', width - boxWidth - padding + 10, padding + 20)

        ctx.font = '12px Arial'
        ctx.fillText(classification.class, width - boxWidth - padding + 10, padding + 40)
        ctx.fillText(`置信度: ${(classification.confidence * 100).toFixed(1)}%`, width - boxWidth - padding + 10, padding + 60)
    }

    const getClassColor = (className: string, index: number): string => {
        const colors = [
            '#ff4d4f', '#1890ff', '#52c41a', '#faad14', '#722ed1',
            '#eb2f96', '#13c2c2', '#fa541c', '#2f54eb', '#a0d911'
        ]
        return colors[index % colors.length]
    }

    const handleZoomIn = () => {
        setViewerState(prev => ({ ...prev, zoom: Math.min(prev.zoom * 1.2, 5.0) }))
    }

    const handleZoomOut = () => {
        setViewerState(prev => ({ ...prev, zoom: Math.max(prev.zoom / 1.2, 0.1) }))
    }

    const handleReset = () => {
        setViewerState(prev => ({ ...prev, zoom: 1.0, pan: [0, 0] }))
    }

    const handleExport = (format: string) => {
        if (onExport) {
            onExport(format)
        } else {
            // 默认导出画布内容
            const canvas = canvasRef.current
            if (canvas) {
                const link = document.createElement('a')
                link.download = `result_visualization.${format}`
                link.href = canvas.toDataURL(`image/${format}`)
                link.click()
            }
        }
    }

    return (
        <Card
            title="结果可视化"
            extra={
                <Space>
                    <Select
                        placeholder="导出格式"
                        style={{ width: 100 }}
                        onSelect={handleExport}
                    >
                        <Option value="png">PNG</Option>
                        <Option value="jpeg">JPEG</Option>
                        <Option value="svg">SVG</Option>
                    </Select>
                    <Button icon={<FullscreenOutlined />} />
                </Space>
            }
        >
            <Row gutter={[16, 16]}>
                {/* 控制面板 */}
                <Col span={6}>
                    <Space direction="vertical" size="middle" className="w-full">
                        {/* 显示控制 */}
                        <Card size="small" title="显示控制">
                            <Space direction="vertical" size="small" className="w-full">
                                <div>
                                    <Text>缩放: {viewerState.zoom.toFixed(1)}x</Text>
                                    <div className="mt-2">
                                        <Button.Group>
                                            <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
                                            <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} />
                                            <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
                                        </Button.Group>
                                    </div>
                                </div>

                                <div>
                                    <div className="flex items-center justify-between mb-2">
                                        <Text>显示覆盖层</Text>
                                        <Switch
                                            checked={viewerState.showOverlay}
                                            onChange={(checked) =>
                                                setViewerState(prev => ({ ...prev, showOverlay: checked }))
                                            }
                                            checkedChildren={<EyeOutlined />}
                                            unCheckedChildren={<EyeInvisibleOutlined />}
                                        />
                                    </div>
                                </div>

                                {viewerState.showOverlay && (
                                    <div>
                                        <Text>透明度</Text>
                                        <Slider
                                            min={0.1}
                                            max={1.0}
                                            step={0.1}
                                            value={viewerState.overlayOpacity}
                                            onChange={(value) =>
                                                setViewerState(prev => ({ ...prev, overlayOpacity: value }))
                                            }
                                        />
                                    </div>
                                )}
                            </Space>
                        </Card>

                        {/* 过滤控制 */}
                        {taskType === 'detection' && (
                            <Card size="small" title="检测过滤">
                                <Space direction="vertical" size="small" className="w-full">
                                    <div>
                                        <Text>置信度阈值</Text>
                                        <Slider
                                            min={0.0}
                                            max={1.0}
                                            step={0.05}
                                            value={viewerState.confidenceThreshold}
                                            onChange={(value) =>
                                                setViewerState(prev => ({ ...prev, confidenceThreshold: value }))
                                            }
                                            marks={{
                                                0: '0',
                                                0.5: '0.5',
                                                1: '1'
                                            }}
                                        />
                                    </div>
                                </Space>
                            </Card>
                        )}

                        {/* 类别选择 */}
                        {availableClasses.length > 0 && (
                            <Card size="small" title="显示类别">
                                <Select
                                    mode="multiple"
                                    placeholder="选择要显示的类别"
                                    value={viewerState.selectedClasses}
                                    onChange={(classes) =>
                                        setViewerState(prev => ({ ...prev, selectedClasses: classes }))
                                    }
                                    style={{ width: '100%' }}
                                >
                                    {availableClasses.map(className => (
                                        <Option key={className} value={className}>
                                            {className}
                                        </Option>
                                    ))}
                                </Select>
                            </Card>
                        )}
                    </Space>
                </Col>

                {/* 可视化区域 */}
                <Col span={18}>
                    <div
                        className="relative border rounded bg-black"
                        style={{ height: '500px', overflow: 'hidden' }}
                    >
                        {loading && (
                            <div className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 z-10">
                                <Spin size="large" />
                            </div>
                        )}

                        <canvas
                            ref={canvasRef}
                            width={800}
                            height={500}
                            className="absolute inset-0"
                            style={{
                                transform: `scale(${viewerState.zoom}) translate(${viewerState.pan[0]}px, ${viewerState.pan[1]}px)`,
                                transformOrigin: 'center'
                            }}
                        />

                        <canvas
                            ref={overlayCanvasRef}
                            width={800}
                            height={500}
                            className="absolute inset-0"
                            style={{
                                transform: `scale(${viewerState.zoom}) translate(${viewerState.pan[0]}px, ${viewerState.pan[1]}px)`,
                                transformOrigin: 'center'
                            }}
                        />

                        {/* 状态信息 */}
                        <div className="absolute bottom-4 left-4 bg-black bg-opacity-70 text-white px-3 py-1 rounded text-sm">
                            缩放: {viewerState.zoom.toFixed(1)}x |
                            结果: {results.length} |
                            类别: {viewerState.selectedClasses.length}
                        </div>
                    </div>

                    {!imageData && (
                        <Alert
                            message="影像数据占位显示"
                            description="实际应用中将显示真实的医学影像数据和分析结果"
                            type="info"
                            showIcon
                            className="mt-4"
                        />
                    )}
                </Col>
            </Row>
        </Card>
    )
}

export default ResultVisualization